import os
import sys

from distutils import log
from pkg_resources import to_filename

import setuptools


def rmdirhier(top):
    for root, dirs, files in os.walk(top, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))


class uninstall(setuptools.Command):
    '''
    Implements the 'uninstall' command.
    '''
    
    user_options = []


    def initialize_options(self):
        self.egg_name = None
        self.install_lib = None
        self.install_scripts = None


    def finalize_options(self):
        self.set_undefined_options('egg_info',
            ('egg_name', 'egg_name'))
        self.set_undefined_options('install',
            ('install_scripts', 'install_scripts'),
            ('install_lib', 'install_lib'))


    def run(self):
        dist = self.distribution

        for s in dist.entry_points.get('console_scripts', []):
            script = os.path.join(self.install_scripts,
                s.split('=')[0].strip())
            try:
                os.stat(script)
            except:
                pass
            else:
                log.info('Removing %s', script)
                os.unlink(script)

        for p in dist.packages:
            if p:
                d = os.path.join(self.install_lib, p)
                log.info('Removing %s', d)
                rmdirhier(d)

        egg = '%s-%s-py%s.egg-info' % (to_filename(self.egg_name),
            dist.get_version(), '.'.join(str(i) for i in sys.version_info[0:2]))
        d = os.path.join(self.install_lib, egg)
        log.info('Removind %s', d)
        rmdirhier(d)
